//
//  selectGroupViewController.m
//  SouthChina
//
//  Created by zorro on 15/7/2.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "selectGroupViewController.h"
#import "ContactDao.h"
#import "selectTableViewController.h"
#import "GroupTableViewCell.h"
#import "selectGroupViewController.h"
#import "CreateGroupViewController.h"
#import "selectMemberViewController.h"
#import "SearchGrpMemberViewController.h"
@interface selectGroupViewController () <UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UnitViewDelegate>
{
    NSMutableArray * groupData;
}
@end

@implementation selectGroupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self addTitleBarWithBackBtn:@"群组列表" needReturn:TRUE];
    
    UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"selectGroupViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];   
    
    _tabGroup.delegate = self;
    _tabGroup.dataSource = self;
    [self refreshTableView];
    
    _searchGroup.delegate = self;
    _searchGroup.placeholder = @"输入用户名或群组名搜索";
    _searchGroup.showsCancelButton=NO;
    _searchGroup.barStyle=UIBarStyleDefault;
    _searchGroup.keyboardType = UIKeyboardTypeDefault;
    
    //需要重新设置
    _selectMemberList.isDoneButton = YES;
    _selectMemberList = [_selectMemberList initWithFrame:_selectMemberList.frame];
    _selectMemberList.delegate = self;
    
    for( Contact * contact in _selectedContact)
    {
        [_selectMemberList addNewUnit:contact];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    //单独跳转到一个搜索页面
    SearchGrpMemberViewController * searchgroup =[[SearchGrpMemberViewController alloc] initWithNibName:nil bundle:nil];
    searchgroup.selectedContact = _selectedContact;
    searchgroup.CreateType = _CreateType;
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:searchgroup animated:YES];
    return  NO;//返回NO不显示键盘
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

-(void) refreshTableView{
    
    NSString * where = [NSString stringWithFormat:@"where org_type='%@' and operate='U'",_GroupType];
    NSMutableArray *array  = [[NSMutableArray alloc] initWithArray:[ContactDao getContactByWhere:where]];
    
    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@"mHAS_CHILD== %@", @"1"];
    NSArray *MyAPP = [array filteredArrayUsingPredicate:predicate1];
    
    NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"mHAS_CHILD== %@", @"0"];
    NSArray *NoMyAPP = [array filteredArrayUsingPredicate:predicate2];
    
    groupData = [[NSMutableArray alloc]init];
    if(MyAPP != nil && MyAPP.count != 0)
    {
        [groupData addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"我管理的群",@"name",MyAPP,@"group", nil]];
    }
    
    if (NoMyAPP != nil && NoMyAPP.count != 0)
    {
        [groupData addObject:[NSDictionary dictionaryWithObjectsAndKeys:@"我加入的群",@"name",NoMyAPP,@"group", nil]];
    }
    
    [_tabGroup reloadData];
}

//
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_selectMemberList removeAll];
    
    for( Contact * contact in _selectedContact)
    {
        [_selectMemberList addNewUnit:contact];
    }
}

//列表组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return groupData.count;
}

//设置列表头信息
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if([_GroupType isEqualToString:@"Chat"])
        return @"";
    else
        return [[groupData objectAtIndex:section] objectForKey:@"name"];
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if([_GroupType isEqualToString:@"Chat"])
        return 0.1;
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if([_GroupType isEqualToString:@"Chat"])
        return 0.1;
    return 10;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    long count = [[[groupData objectAtIndex:section] objectForKey:@"group"] count];
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * CellIdentifier = @"GroupTableViewCell";
    GroupTableViewCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
        cell.imgHead.layer.masksToBounds = YES;
        cell.imgHead.layer.cornerRadius = 16;
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
 
    Contact *group =  [[[groupData objectAtIndex:indexPath.section] objectForKey:@"group"] objectAtIndex:indexPath.row];
    cell.labTitle.text = group.mNAME;
    
    NSURL *url = [NSURL URLWithString:group.mHEAD_IMG];
    [cell.imgHead setImageWithURL:url placeholderImage:[UIImage imageNamed:@"empty_photo"]];
    
    return  cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    //选种的单元格信息
    Contact * contact = [[[groupData objectAtIndex:indexPath.section] objectForKey:@"group"] objectAtIndex: indexPath.row];
    
    selectTableViewController * selectTable = [[selectTableViewController alloc] init];
    selectTable.curOrgContact = contact;
    selectTable.selectedContact = _selectedContact;
    selectTable.CreateType = _CreateType;
    
    [kAppDelegate.iCSDrawerController.navigationController pushViewController:selectTable animated:YES];
}


- (void) extendCellTouched:(UnitCell *)unitCell
{
    //点击选择好的成员后，需要清理数据
    Contact *contact =unitCell.contact;
    for (Contact * i   in  _selectedContact)
    {
        
        if ([i.mID isEqualToString:contact.mID]) {
            [_selectedContact removeObject:i];
            break;
        }
    }
}

- (void) unitDoneTouched:(id)sender
{
    if([_CreateType isEqualToString:CREATETYPE_CREATEGROUP])
    {
        for (UIViewController *temp in kAppDelegate.iCSDrawerController.navigationController.viewControllers) {
            if ([temp isKindOfClass:[CreateGroupViewController class]]) {
                [kAppDelegate.iCSDrawerController.navigationController popToViewController:temp animated:YES];
            }
        }
    }
    else if([_CreateType isEqualToString:CREATETYPE_CREATECHAT])
    {
        //创建讨论组
        if(_selectedContact.count >200 || _selectedContact.count <2)
        {
            [self showAlerHUD:@"添加的成员人数不能小于2人和大于200人"];
            return;
        }
        
        /*"groupType":"1", --群组类型1 普通群 2 行政群 3 讨论组
         "userIds":"9004,9005,9006",--添加的用户列表，用逗号隔开 选填
         "groupName":"信网中心群",--群名称 选填
         "groupTags":"72,73,81",--群标签，多个值用逗号隔开 选填
         "toMountGroupId":"10000736",--挂靠的群组Id选填*/
        
        NSEnumerator *enumerator = [_selectedContact objectEnumerator];
        NSMutableString *ids = [[NSMutableString alloc] initWithString:@""];
        [ids insertString:[NSString stringWithFormat:@"%@,",DE.userId] atIndex:0];
        for (Contact *cid in enumerator) {
            [ids insertString:[NSString stringWithFormat:@"%@,",cid.mID] atIndex:0];
        }
        
        NSDictionary *dict  = @{@"groupType":@"3",
                                @"userIds":ids,
                                @"groupName":@"",
                                @"groupTags":@"",
                                @"toMountGroupId":@""};
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [DE serverCall:@"createGrp" params:dict callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if (success) {
                NSString *addVersion = [DE getGlobalVar:[NSString stringWithFormat:@"%@_%@", [DE getGlobalVar:LOGIN_USER_REALID],[DE getGlobalVar:CONTACT_VERSION]]];
                NSDictionary *userInfo = @{@"AddressBookVersion":addVersion==nil?@"0":addVersion};
                
                [DE serverCall:@"refreshAdBook" params:userInfo callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    
                    if(success){
                        @try {
                            [DE updateLocalDBContacts:[data objectForKey:@"txl"] sessionId:nil businessId:nil sendout:YES];
                            UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建成功！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:nil, nil];
                            [view show];
                        }
                        @catch (NSException *exception) {
                            [self showAlerHUD:@"创建讨论组失败！"];
                        }
                        
                    }else{
                        [self showAlerHUD:@"创建讨论组失败！"];
                        
                    }
                    
                }];
                
            }else{
                
                UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"提示" message:@"创建失败！" delegate:self cancelButtonTitle:@"返回上一级" otherButtonTitles:@"确定", nil];
                [view show];
            }
            
        }];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (buttonIndex==0) {
        [kAppDelegate.iCSDrawerController.navigationController popToRootViewControllerAnimated:NO];
    }
}


@end
